package ch02.classPath;

import ch02.classPath.Entry.Entry;
import ch02.classPath.Entry.WildcardEntry;

import java.io.File;
import java.io.IOException;

public class ClassPath {
    private Entry bootClasspath;
    private Entry extClasspath;
    private Entry userClasspath;

    private String jreDir;

    public ClassPath(String jreOption, String cpOption){
        jreDir = getJreDir(jreOption);
        bootClasspath = parseBootClasspath();
        extClasspath = parseExtClasspath();
        userClasspath = parseUserClasspath(cpOption);
    }

    private Entry parseUserClasspath(String path) {
        try {
            //如果用户没有显示设置 cp ，那么就是当前目录作为 cp
            if (path==null){
                path = "";
            }
            return Entry.createEntry(path);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    private Entry parseExtClasspath() {
        //可能出现的情况是: /jre/lib/ext/*
        String jreExtPath = jreDir + File.separator + "lib" + File.separator + "ext" + File.separator + "*";
        return new WildcardEntry(jreExtPath);
    }

    private Entry parseBootClasspath() {
        //可能出现的情况是：/jre/lib*
        String jreLibPath = jreDir + File.separator + "lib" + File.separator + "*";
        return new WildcardEntry(jreLibPath);
    }

    /**
     * 1.先找 jreOption 路径
     * 2.从当前目录找
     * 3.从 JAVA_HOME 中找
     * @param jreOption
     * @return
     */
    private String getJreDir(String jreOption) {
        File jreFile;
        if(jreOption != null && !"".equals(jreOption)){
            jreFile = new File(jreOption);
            if(jreFile.exists()){
                return jreOption;
            }
        }

        //从当前目录找
        jreFile = new File("jre");
        if(jreFile.exists()){
            return jreFile.getAbsolutePath();
        }

        //从JAVA_HOME目录找
        String java_home = System.getenv("JAVA_HOME");
        if(java_home != null){
            return java_home + File.separator + "jre";
        }

        throw new RuntimeException("Can not find jre folder!");
    }

    //遍历三个路径加载类
    public byte[] readClass(String className) {
        byte[] classData;

        String className_suff = className + ".class";

        try {
            if((classData=bootClasspath.readClass(className_suff)) != null){
                return classData;
            }else if((classData = extClasspath.readClass(className_suff))!= null){
                return classData;
            }else if((classData = userClasspath.readClass(className_suff)) != null){
                return classData;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        throw new RuntimeException("can't find class!");
    }

}
